﻿using System.Web;
using Foothill.Model;
using Foothill.Service.Session;
using Foothill.Service.UserAccount;

namespace Foothill.Service.Security
{
    public class SecurityService : ISecurityService
    {
        private ISessionService _sessionService;

        private IUserAccountService _userAccountService;

        public SecurityService(ISessionService sessionSvc, IUserAccountService userAccountService)
        {
            _sessionService = sessionSvc;
            _userAccountService = userAccountService;
        }
        
        public bool IsCurrentUserAuthenticated()
        {
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }

        public CurrentLoginUser GetLoginUserDetails()
        {
            if (!IsCurrentUserAuthenticated())
            {
                return null;
            }

            object obj = _sessionService.GetSessionValue(SessionNames.LoginUser);
            CurrentLoginUser result = obj as CurrentLoginUser;

            if (result == null)
            {
                // somehow session is lost
                result = new CurrentLoginUser(_userAccountService.GetUserAccountDetailsByUserName(HttpContext.Current.User.Identity.Name));
                _sessionService.SaveSessionValue(SessionNames.LoginUser, result);
            }

            return result;
        }

        public int GetLoginUserId()
        {
            int loginUserId = -1;
            CurrentLoginUser currentLoginUser = GetLoginUserDetails();

            if (currentLoginUser != null)
            {
                UserAccountDto user = GetLoginUserDetails().UserAccountInfo;
                if (user != null)
                {
                    loginUserId = user.UserAccountId;
                }
            }

            return loginUserId;
        }
    }
}
